import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-04-21
 * Time: 12:24
 */

public class HashBucket {
    public int usedSize;
    public double loadFactor = 0.75;

    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public HashBucket() {
        arr = new Node[10];
    }

    public Node[] arr;//存放头结点

    //插入
    public void put(int key, int value) {
        int index = key % arr.length;
        Node cur = arr[index];
        while (cur != null) {
            //看看有没有key,如果有更新value
            if (cur.key == key) {
                cur.val = value;
                return;
            }
            cur = cur.next;
        }
        //没有key
        Node node = new Node(key, value);//新的数据
        node.next = arr[index];
        arr[index] = node;
        usedSize++;
        if (arr.length * 1.0 / usedSize > loadFactor) {
            resize();//扩容
        }
    }

    private void resize() {
        Node[] tmp = new Node[arr.length * 2];//存放头结点
        //重新哈希
        for (int i = 0; i < arr.length; i++) {
            Node cur = arr[i];
            while (cur != null) {
                int newIndex = cur.key % (tmp.length);
                Node curN = cur.next;
                tmp[newIndex] = cur;
                cur = curN;
            }
        }
        arr = tmp;
    }

    //获取key的value
    public int get(int key) {
        int index = key % arr.length;
        Node cur = arr[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

}
